<template>
  <div class="group-stage">
    <div class="buttons">
      <el-button
        type="primary"
        icon="el-icon-plus"
        @click="showAdd = true"
        size="small">新增团期</el-button>
    </div>
    <template>
      <el-table
        :default-expand-all="true"
        :data="items">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <div class="collection-item" style="background-color: #f4f4f4">
              <div class="item">上车点</div>
              <div class="item">人数限制</div>
              <div class="item">出发时间</div>
              <div class="item">操作</div>
            </div>
            <template v-for="(collection, idx) in scope.row.collection_point">
              <div class="collection-item" :key="'collection_' + scope.$index + '_' + idx">
                <div class="item">
                  <el-tooltip class="item" effect="dark" :content="collection.address" placement="top">
                    <span style="padding-left: 0">{{collection.title}}</span>
                  </el-tooltip>
                </div>
                <div class="item">{{collection.limit}}</div>
                <div class="item">{{collection.set_out_time}}</div>
                <div class="item">
                  <el-button
                    type="primary"
                    @click="
                    showUpdateCollectionPoint = true;
                    editCollectionPointIndex = idx;
                    editCollectionPointGroupStageIndex = scope.$index;
                    updateCollectionData.id = collection.id;
                    updateCollectionData.limit = collection.limit;
                    updateCollectionData.set_out_time = collection.set_out_time;"
                    size="little">编辑</el-button>
                  <el-button
                    type="danger"
                    @click="deleteCollectionPoint(scope.$index, idx)"
                    size="little">删除</el-button>
                </div>
              </div>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="出行日期">
          <template slot-scope="scope">{{scope.row.start_time}}至{{scope.row.end_time}}</template>
        </el-table-column>
        <el-table-column label="截止报名时间">
          <template slot-scope="scope">{{scope.row.apply_end_date}}</template>
        </el-table-column>
        <el-table-column label="成人价">
          <template slot-scope="scope">{{Number(scope.row.adult_price).toFixed(2)}}</template>
        </el-table-column>
        <el-table-column label="儿童价">
          <template slot-scope="scope">{{Number(scope.row.kid_price).toFixed(2)}}</template>
        </el-table-column>
        <el-table-column label="保险类型">
          <template slot-scope="scope">{{({1: '无需保险', 2: '统一购买', 3: '自购保险'})[scope.row.insurance_type]}}</template>
        </el-table-column>
        <el-table-column label="保险价格">
          <template slot-scope="scope">{{Number(scope.row.insurance_price).toFixed(2)}}</template>
        </el-table-column>
        <el-table-column label="报名人数上限">
          <template slot-scope="scope">
            {{sumSignUpLimit(scope.row.collection_point)}}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="success"
              @click="showCollectionPointDialog(); collectionPointIndex = scope.$index"
              size="little">添加集合点</el-button>
            <el-button
              type="primary"
              @click="updateForm = scope.row; updateIndex = scope.$index; showUpdate = true;"
              size="little">编辑</el-button>
            <el-button
              type="danger"
              @click="deleteOne(scope.$index)"
              size="little">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <!--添加集合点-->
    <template>
      <el-dialog
        title="添加集合点"
        :close-on-click-modal="false"
        :show-close="false"
        :visible.sync="showCreateCollectionPoint">
        <el-form :model="createCollectionData">
          <el-form-item label="集合点" label-width="100px">
            <el-select v-model="createCollectionData.id" filterable placeholder="输入关键词搜索" style="width: 220px">
              <el-option
                v-for="(item, idx) in collectionPointItems"
                :key="'create_collection_point_' + idx"
                :label="item.title"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="人数限制" label-width="100px">
            <el-input
              type="number"
              v-model="createCollectionData.limit"
              style="max-width: 220px">
            </el-input>
          </el-form-item>
          <el-form-item label="上车时间" label-width="100px">
            <el-date-picker
              v-model="createCollectionData.set_out_time"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="请选择上车时间"
              :picker-options="pickerOptions"
              default-time="07:00:00">
            </el-date-picker>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="showCreateCollectionPoint = false">取 消</el-button>
          <el-button type="primary" @click="submitForCreateCollectionPoint">确 定</el-button>
        </div>
      </el-dialog>
    </template>
    <!-- 编辑集合点-->
    <template>
      <el-dialog
        title="编辑集合点"
        :close-on-click-modal="false"
        :show-close="false"
        :visible.sync="showUpdateCollectionPoint">
        <el-form :model="updateCollectionData">
          <el-form-item label="集合点" label-width="100px">
            <el-select v-model="updateCollectionData.id" filterable placeholder="输入关键词搜索" style="width: 220px">
              <el-option
                v-for="(item, idx) in collectionPointItems"
                :key="'create_collection_point_' + idx"
                :label="item.title"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="人数限制" label-width="100px">
            <el-input
              type="number"
              v-model="updateCollectionData.limit"
              style="max-width: 220px">
            </el-input>
          </el-form-item>
          <el-form-item label="上车时间" label-width="100px">
            <el-date-picker
              v-model="updateCollectionData.set_out_time"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="请选择上车时间"
              :picker-options="pickerOptions"
              default-time="07:00:00">
            </el-date-picker>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="showUpdateCollectionPoint = false">取 消</el-button>
          <el-button type="primary" @click="submitForUpdateCollectionPoint">确 定</el-button>
        </div>
      </el-dialog>
    </template>
    <!--新增-->
    <template>
      <el-dialog
        title="新增团期"
        :close-on-click-modal="false"
        :show-close="false"
        :visible.sync="showAdd">
        <el-form :model="form">
          <el-form-item label="日期" label-width="100px">
            <el-col :span="24">
              <el-date-picker
                v-model="period"
                type="daterange"
                value-format="yyyy-MM-dd"
                range-separator="至"
                :picker-options="pickerOptions"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-col>
          </el-form-item>
          <el-form-item label="报名截止日期" label-width="100px">
            <el-date-picker
              type="date"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions"
              placeholder="报名截止日期"
              v-model="form.apply_end_date"></el-date-picker>
          </el-form-item>
          <el-form-item label="成人价格" label-width="100px">
            <el-input
              v-model="form.adult_price"
              style="max-width: 220px"
              type="number"
              placeholder="0.00">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item
            label="儿童价格"
            label-width="100px">
            <el-input
              type="number"
              v-model="form.kid_price"
              style="max-width: 220px"
              placeholder="0.00">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item
            label="保险"
            label-width="100px">
            <el-radio-group v-model="form.insurance_type">
              <el-radio :label="2">统一购买</el-radio>
              <el-radio :label="3">自购保险</el-radio>
              <el-radio :label="1">无需保险</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="保险价格"
            label-width="100px">
            <el-input
              v-model="form.insurance_price"
              style="max-width: 220px"
              placeholder="0.00">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="showAdd = false">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </div>
      </el-dialog>
    </template>
    <!-- 修改-->
    <template>
      <el-dialog
        title="修改团期"
        :close-on-click-modal="false"
        :show-close="false"
        :visible.sync="showUpdate">
        <el-form :model="updateForm">
          <el-form-item label="出发日期" label-width="100px">
            <el-date-picker
              v-model="updatePeriod"
              type="daterange"
              value-format="yyyy-MM-dd"
              range-separator="至"
              :picker-options="pickerOptions"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="报名截止日期" label-width="100px">
            <el-date-picker
              type="date"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions"
              placeholder="报名截止日期"
              v-model="updateForm.apply_end_date"></el-date-picker>
          </el-form-item>
          <el-form-item label="成人价格" label-width="100px">
            <el-input
              v-model="updateForm.adult_price"
              style="max-width: 220px"
              type="number"
              placeholder="0.00">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item
            label="儿童价格"
            label-width="100px">
            <el-input
              type="number"
              v-model="updateForm.kid_price"
              style="max-width: 220px"
              placeholder="0.00">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item
            label="保险"
            label-width="100px">
            <el-radio-group v-model="updateForm.insurance_type">
              <el-radio :label="2">统一购买</el-radio>
              <el-radio :label="3">自购保险</el-radio>
              <el-radio :label="1">无需保险</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="保险价格"
            label-width="100px">
            <el-input
              v-model="updateForm.insurance_price"
              style="max-width: 220px"
              placeholder="0.00">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="showUpdate = false">取 消</el-button>
          <el-button type="primary" @click="submitForUpdate">确 定</el-button>
        </div>
      </el-dialog>
    </template>
  </div>
</template>
<script>
  export default {
    props: {
      formData: {
        type: Object
      }
    },
    data () {
      return {
        period: [],
        updatePeriod: [],
        // 集合点列表
        collectionPointItems: [],
        // 添加集合点时团期数据的索引
        collectionPointIndex: null,
        // 修改集合点时团期数据的索引
        editCollectionPointGroupStageIndex: null,
        // 修改集合点时集合点的索引
        editCollectionPointIndex: null,
        // element-ui date picker组件参数
        pickerOptions: {},
        // 是否显示添加集合点弹窗
        showCreateCollectionPoint: false,
        // 是否显示编辑集合点弹窗
        showUpdateCollectionPoint: false,
        // 是否显示添加团期弹窗
        showAdd: false,
        // 是否显示修改团期弹窗
        showUpdate: false,
        // 添加集合点时的临时数据
        createCollectionData: {
          id: '',
          limit: '',
          set_out_time: ''
        },
        // 编辑集合点时的临时数据
        updateCollectionData: {
          id: '',
          limit: '',
          set_out_time: ''
        },
        lng: '',
        lat: '',
        form: {
          // 成人价格
          adult_price: '',
          // 小孩价格
          kid_price: '',
          // 开始日期
          start_time: '',
          // 结束日期
          end_time: '',
          // 截止报名日期
          apply_end_date: '',
          // 保险类型
          insurance_type: 2,
          // 保险价格
          insurance_price: '',
          collection_point: []
        },
        // 团期数据
        items: [],
        // 修改团期时的列表索引
        updateIndex: '',
        // 修改团期时的临时数据
        updateForm: {}
      }
    },
    methods: {
      /**
       * @purpose 修改集合点
       */
      submitForUpdateCollectionPoint () {
        if (!this.updateCollectionData.id) {
          this.toast('请选择集合点', 'warning')
          return false
        }
        if (!this.updateCollectionData.limit) {
          this.toast('请填写限制人数', 'warning')
          return false
        }
        if (!this.updateCollectionData.set_out_time) {
          this.toast('请选择当天的上车时间', 'warning')
          return false
        }
        // 新数据
        let collection = {}
        this.collectionPointItems.map(item => {
          if (Number(item.id) === Number(this.updateCollectionData.id)) {
            collection = item
            collection.limit = this.updateCollectionData.limit
            collection.set_out_time = this.updateCollectionData.set_out_time
          }
        })
        // 替换数据
        this.items = this.items.map((item, idx) => {
          if (idx === this.editCollectionPointGroupStageIndex) {
            item.collection_point = item.collection_point.map((_item, _idx) => {
              if (_idx === this.editCollectionPointIndex) {
                _item = collection
              }
              return _item
            })
          }
          return item
        })
        this.showUpdateCollectionPoint = false
        this.toast('编辑成功')
        // 重置数据
        this.updateCollectionData = {
          id: '',
          limit: '',
          set_out_time: ''
        }
      },
      /**
       * @purpose 删除集合点
       */
      deleteCollectionPoint (groupStageIdx, collectionPointIdx) {
        this.$confirm('确定要删除吗? 删除之后不可恢复', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.items = this.items.map((item, idx) => {
            if (groupStageIdx === idx) {
              item.collection_point = item.collection_point.filter((_, _idx) => {
                return (_idx !== collectionPointIdx)
              })
            }
            return item
          })
          this.toast('删除成功')
        }).catch(r => {})
      },
      /**
       * 计算报名上限人数
       */
      sumSignUpLimit (data) {
        if (!data) {
          return 0
        }
        let sum = 0
        data.forEach(item => {
          sum += Number(item.limit)
        })
        return sum
      },
      /**
       *  添加集合点
       */
      submitForCreateCollectionPoint () {
        if (!this.createCollectionData.id) {
          this.toast('请选择集合点', 'warning')
          return false
        }
        if (!this.createCollectionData.limit) {
          this.toast('请填写限制人数', 'warning')
          return false
        }
        if (!this.createCollectionData.set_out_time) {
          this.toast('请选择当天的上车时间', 'warning')
          return false
        }
        let collection = {}
        this.collectionPointItems.map(item => {
          if (Number(item.id) === Number(this.createCollectionData.id)) {
            collection = item
          }
        })
        this.items = this.items.map((item, idx) => {
          if (idx === this.collectionPointIndex) {
            collection.limit = this.createCollectionData.limit
            collection.set_out_time = this.createCollectionData.set_out_time
            item.collection_point.push(collection)
          }
          return item
        })
        this.showCreateCollectionPoint = false
        this.toast('添加成功')
        // 重置数据
        this.createCollectionData = {
          id: '',
          limit: '',
          set_out_time: ''
        }
      },
      /**
       * 显示添加集合点弹出框
       */
      showCollectionPointDialog () {
        if (!this.formData.address_info.city.id) {
          this.toast('请先选择市级区域', 'warning')
          return false
        }
        this.showCreateCollectionPoint = true
        this.getCollectionPointItems()
      },
      /**
       *  @purpose 获取集合点信息
       */
      getCollectionPointItems () {
        this.collectionPointItems = []
        this
          .$api
          .collectionPoint
          .itemsByCity(this.formData.address_info.city.id)
          .then(r => {
            if (r.length < 1) {
              this.toast('该市区暂无集合点,请先添加')
              return false
            }
            this.collectionPointItems = r
          })
      },
      /**
       * 删除一条团期数据
       */
      deleteOne (index) {
        this.$confirm('确定要删除吗? 删除之后不可恢复', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.items = this.items.filter((_, idx) => {
            return (index !== idx)
          })
          this.toast('删除成功')
        }).catch(r => {})
      },
      /**
       *  修改团期
       */
      submitForUpdate () {
        if (!this.updateForm.start_time) {
          this.toast('请选择日期', 'warning')
          return false
        }
        if (!this.updateForm.apply_end_date) {
          this.toast('请选择报名截止日期', 'warning')
          return false
        }
        if (!this.updateForm.adult_price) {
          this.toast('请填写成人价格', 'warning')
          return false
        }
        if (!this.updateForm.kid_price) {
          this.toast('请填写儿童价格', 'warning')
          return false
        }
        if (!this.updateForm.insurance_price) {
          this.toast('请填写保险价格', 'warning')
          return false
        }
        this.items = this.items.map((item, idx) => {
          if (idx === this.updateIndex) {
            item = this.updateForm
          }
          return item
        })
        this.toast('编辑成功')
        this.showUpdate = false
      },
      /**
       * @purpose 保存数据到本地缓存
       * @returns {boolean}
       */
      submit () {
        if (!this.form.start_time) {
          this.toast('请选择出发日期', 'warning')
          return false
        }
        if (!this.form.apply_end_date) {
          this.toast('请选择报名截止日期', 'warning')
          return false
        }
        if (!this.form.adult_price) {
          this.toast('请填写成人价格', 'warning')
          return false
        }
        if (!this.form.kid_price) {
          this.toast('请填写儿童价格', 'warning')
          return false
        }
        if (!this.form.insurance_price) {
          this.toast('请填写保险价格', 'warning')
          return false
        }
        this.items.push(this.form)
        this.toast('保存成功,当前数据仅保存在本地,请勿刷新界面,保存活动信息时会自动保存!')
        this.showAdd = false
      }
    },
    watch: {
      updateForm (val) {
        this.updatePeriod = [
          val.start_time, val.end_time
        ]
      },
      period (val) {
        this.form.start_time = val[0]
        this.form.end_time = val[1]
      },
      updatePeriod (val) {
        this.updateForm.start_time = val[0]
        this.updateForm.end_time = val[1]
      },
      showUpdateCollectionPoint (val) {
        if (val) {
          if (!this.formData.address_info.city.id) {
            this.toast('请先选择市级区域', 'warning')
            this.showUpdateCollectionPoint = false
            return false
          }
          this.getCollectionPointItems()
        }
      },
      /**
       * @purpose 监听到数据变化,缓存到localStorage里面去
       * @param val
       */
      items (val) {
        this.storage().set('add-group-stage', val)
        this.$emit('callback', val)
      },
      /**
       * @purpose 清除数据
       * @param val
       */
      showAdd (val) {
        if (!val) {
          this.form = {
            // 成人价格
            adult_price: '',
            // 小孩价格
            kid_price: '',
            // 开始日期
            start_time: '',
            // 结束日期
            end_time: '',
            // 截止报名日期
            apply_end_date: '',
            // 保险类型
            insurance_type: 2,
            // 保险价格
            insurance_price: '',
            collection_point: []
          }
        }
      }
    },
    created () {
      this.pickerOptions = Object.assign({}, this.pickerOptions, {
        disabledDate: (time) => {
          return (time.getTime() + 3600 * 24) < this.getDayStartTimeStamp()
        }
      })
      let items = this.storage().get('add-group-stage')
      if (items instanceof Array && items.length > 0) {
        this.items = items
      }
    }

  }
</script>
<style lang="sass">
  .el-table__expanded-cell[class*=cell]
    padding: 20px 0 20px 50px
    .item
      .el-button--little.el-button + .el-button
        margin: 0 0 0 5px
</style>
<style scoped lang="sass">
  .group-stage
    width: 100%
    height: 100%
    .collection-item
      width: 100%
      min-height: 41px
      display: flex
      align-items: center
      justify-content: center
      &:hover
        background-color: #f4f4f4
      .item
        height: 100%
        flex: 1
        display: flex
        align-items: center
        padding-left: 1rem
</style>
